package com.hutao.chargingpile.oss.controller.api;

import com.hanhan.common.exception.BusinessException;
import com.hanhan.common.result.R;
import com.hanhan.common.result.ResponseEnum;
import com.hutao.chargingpile.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@Api(tags = "阿里云文件管理")
@CrossOrigin
@RestController
@RequestMapping("/api/oss/file")
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(
            @ApiParam(value = "文件",required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块",required = true)
            @RequestParam("module")String module
            ){
        System.out.println("module === "+module);
        try {
            InputStream inputStream = file.getInputStream();
            System.out.println("进来了try");
            String fileName = file.getOriginalFilename();
            String url = fileService.upload(inputStream, module, fileName);
            return R.ok().message("文件上传成功").data("url",url);
        } catch (IOException e) {
            System.out.println("报错了呢");
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("文件删除")
    @DeleteMapping("/removeFile")
    R remove(@ApiParam(value = "要删除的文件",required = true) @RequestParam("url")String url){
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }
}
